/**
 * User: xpk
 * Date: 12-9-6
 * Time: 下午9:35
 */
/**
 * 功能说明：
 *
 * @author: xpk
 * @Date: 12-7-22
 * @Time: 下午3:24
 */

var CSIT = csit = App = APP = app = {};
window.console = window.console || {
    log:function () {
        //
    }
};
//window.onerror = function (a, b, c) {
//    console.log(['脚本异常：', a, b, c].join('\n'));
//    return true;
//};

//source loader
CSIT.$_reources = {};
CSIT.loadSource = function (type, uri, callback) {
    if (CSIT.$_reources[uri]) {
        if (callback) {
            callback();
        }
        return;
    }
    var head = document.getElementsByTagName('head')[0];
    if (type == 'css') {
        //<link href="res/css/style.css" type="text/css" rel="stylesheet">
        var style = document.createElement("link");
        style.setAttribute('href', uri);
        style.setAttribute('rel', 'stylesheet');
        style.setAttribute('type', 'text/css');
        if (callback) {
            style.onload = function () {
                callback();
                style.onload = null;
            }
        }
        head.appendChild(style);
    } else if (type == 'js' || type == 'javascript') {

        //<script type="text/javascript" src="app/user/user.model-1.0.js"></script>
        var script = document.createElement("script");
        script.setAttribute('src', uri);
        script.setAttribute('type', 'text/javascript');
        if (callback) {
            script.onload = function () {
                callback();
                script.onload = null;
            }
        }
        head.appendChild(script);
    }
    CSIT.$_reources[uri] = true;
};

CSIT.showError = function (msg) {
    alert(msg);
};
CSIT.getBaseURL = function () {
//
//    if (CSIT.localDebug) {
    jQuery.support.cors = true;     //jquery 1.7控制跨域
//    }
//    if (CSIT.localDebug) {
//        return "test/";
//    } else
    if (window['CSITBaseURL']) {
        return window['CSITBaseURL'];
    } else if (CSIT['baseURL']) {
        return CSIT['baseURL'];
    } else {
        return location.href.split('/').slice(0, 3).join('/') + '/';
    }
};

CSIT.id_index = 0;
CSIT.genId = function () {
    return 'CSIT_UI_' + (CSIT.id_index++);
};
CSIT.empty_row = {rows:[]};
CSIT.empty_row_total = {rows:[],total:1};
CSIT.join ='^'; 

CSIT.ns = function (str) {
    var strs = str.split('.');
    var lastObj;
    if (strs.length == 0) {
        if (!window[str]) {
            window[str] = {};
        }
        return;
    }
    lastObj = window;
    for (var i = 1; i < strs.length; i++) {
        var nLastObj = lastObj[strs.slice(i - 1, i)];
        if (!nLastObj) {
            lastObj[strs.slice(i - 1, i)] = {};
            lastObj = lastObj[strs.slice(i - 1, i)];
        }
    }
    return lastObj;
};

CSIT.setUpAjax = function () {
    $.ajaxSetup({
        error:function (x, e) {
            console.log(this);
            console.log(x);
            console.log(e);
            if (x.status == 0) {
                app.showError('功能未实现或你处于离线状态!.');
            } else if (x.status == 404) {
                app.showError('地址不存在或功能未实现.(' + this.url + ')');
            } else if (x.status == 403) {
                app.showError('服务器返回结果格式不正确.|' + x.responseText);
            } else if (x.status == 500) {
                app.showError('服务器处理异常!');
            } else if (e == 'parsererror') {
                app.showError('服务器返回结果格式不正确');
            } else if (e == 'timeout') {
                app.showError('访问超时，请重试.');
            } else {
                app.showError('未知错误:| status:' + x.status);
            }
        }
    });
};

(function () {
    var oneRender = function () {
        var athis = $(this);
        var uistr = athis.attr('ui');
        athis.removeAttr('ui');
        athis.removeClass('cui');
        var uis;
        if (uistr.indexOf('[') == 0)
            try {
                eval('uis=' + uistr + ';');
            } catch (e) {
            }
        else uis = uistr;
        if (typeof(uis) == 'string')uis = [uis];

        $(uis).each(function () {
            var uiName = this;
            if (!athis.attr('c-init-' + uiName)) {
                var optStr = athis.attr(uiName + '-options');
                athis.removeAttr(uiName + '-options');
                if (optStr) {
                    var opts = {};
                    try {
                        var x = 'opts=' + optStr + ';';
//                        alert(x);
                        eval(x);
                    } catch (e) {
                        console.log('error:' + uiName + '-options=' + optStr);
                    }
                }
                if ($.fn[uiName]) {
                    athis[uiName](opts)
                } else if (athis.attr('module') && athis.attr('action')) {
                    var js = CSIT.getBaseURL() + 'app/' + athis.attr('module') + '/' + '/ctrl/' + athis.attr('action') + '.js';
                    $.xLazyLoader({
                        js:js,
                        success:function () {
                            athis[uiName](opts);
                        }
                    })
                } else if (uiName.indexOf('Init') == uiName.length - 4) {
                    var js = uiName;
                    if (js.indexOf('Init') == js.length - 4) {
                        js = js.substring(0, js.indexOf('Init'))
                    }
                    js = 'js/plugins/' + js + 'Plugins.js?t=' + new Date().getTime();
                    $.xLazyLoader({
                        js:js,
                        success:function () {
                            athis[uiName](opts);
                        }
                    })
                }
                ;
            }
            athis.attr('c-init-' + uiName);
        });
    };
    CSIT.initContent = function (els) {
        return $(els).each(function () {
            var el = $(this);
            if (el.hasClass('cui') || el.attr('ui')){
                oneRender.apply(el, []);
            }
            $('.cui,[ui]', el).each(function () {
                oneRender.apply(this, []);
            });
            return el;
        })
    };
})();
